package cn._2dland.leech;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

@SuppressWarnings("rawtypes")
public final class LeechFactory {

	/** leech映射表 */
	private static Map<String, List<Class>> leechMap;

	static {
		init();
	}

	public static void init() {
		leechMap = new HashMap<String, List<Class>>();

		try {
			String path = System.getProperty("user.dir");
			path = path + File.separator + "leech.xml";

			// 读取XML
			SAXReader reader = new SAXReader();
			Document doc = reader.read(new File(path));
			Element root = doc.getRootElement();

			for(Object obj : root.elements("leech")) {
				Element leech = (Element)obj;

				// 获取leech实现类
				String clsName = leech.elementText("class");
				Class cls = null;
				try { cls = Class.forName(clsName);
				} catch (Exception e) { continue; }

				// 获取网盘的支持
				for(Object spt: leech.elements("support")) {
					String site = ((Element)spt).getText();

					List<Class> clses = leechMap.get(site);
					if(clses == null)
						clses = new ArrayList<Class>();
					clses.add(cls);
					leechMap.put(site, clses);
				}
			}

		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public static LeechClient getLeech(String url) {
		LeechClient client = null;

		try {
			String site = getSiteName(url);
			if(site == null)
				throw new Exception("未知地址！");

			List<Class> clses = leechMap.get(site);
			if(clses == null || clses.size() <= 0)
				throw new Exception("不支持的地址！");

			client = (LeechClient)clses.get(0).newInstance();
		} catch (Exception e) {
			e.printStackTrace(System.err);
		}

		return client;
	}

	private static String getSiteName(String url) {
		String siteName = null;

		Matcher m = Pattern.compile("http://www\\.\\w+\\.com").matcher(url);
		if(m.find()) {
			siteName = url.substring(m.start() + 11, m.end() - 4);
		}
		return siteName;
	}
}
